//https://leetcode.cn/problems/rotting-oranges/submissions/531619605/?envType=daily-question&envId=2024-05-13

class Solution {
public:
    int orangesRotting(vector<vector<int>>& grid) {
            queue<pair<int,int>>q;
            int x[4]={1,-1,0,0};
            int y[4]={0,0,1,-1};
            int m=grid.size();
            int num=0,ans=0;
            int n=grid[0].size();
            for(int i=0;i<m;i++){
                for(int j=0;j<n;j++){
                    if(grid[i][j]==2){
                        q.push({i,j});
                    }
                    if(grid[i][j]==1){
                        num++;
                    }
                }
            }
        while(!q.empty()&&num>0){
            cout<<"num="<<num<<endl;
            ans++;
            int sz=q.size();
            while(sz--){
                pair<int,int> p=q.front();
                q.pop();
                int a=p.first;int b=p.second;
                for(int i=0;i<4;i++){
                    int o=a+x[i];int p=b+y[i];
                    if(o>=0&&p>=0&&o<m&&p<n&&grid[o][p]==1){
                        q.push({o,p});
                        grid[o][p]=2;
                        num--;
                    }
                }
            }

        }
        return num==0?ans:-1;
    }
};